<?php
namespace app\controller;

trait ApiResponse
{
    /**
     * 返回处理
     */
    public static function returnMsg($code = 200, $status = 'success', $message = '', $data = [], $header = [])
    {
        http_response_code($code);
        $return['code'] = (int)$code;
        $return['msg'] = $message;
        $return['status'] = $status;
        if(!empty($data)){
            $return['data'] = $data;
        }

        //发送头部信息
        foreach ($header as $name => $val) {
            if (is_null($val)) {
                header($name);
            } else {
                header($name . ':' . $val);
            }
        }

        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Credentials: true');// 支持cookie跨域
        exit(json_encode($return, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 验证请求方式，默认为GET方式
     * @param $method
     */
    public static function checkMethod($method)
    {
        if (empty($method)) {
            $method = 'GET';
        }

        ApiResponse::returnMsg(405, 'error', '发起请求的方式不正确，请使用 [ ' . $method . ' ] 方式请求');
    }

    /**
     * 返回成功
     * @param string $message
     * @param array $data
     */
    public static function returnSuccess($message = '', $data = null)
    {
        if (empty($data)) {
            ApiResponse::returnMsg(200, 'success', $message);
        } else {
            ApiResponse::returnMsg(200, 'success', $message, $data);
        }
    }

    /**
     * 返回文件资源
     * @param string $message
     * @param array $data
     */
    public static function returnFile($message = '', $data = null)
    {
        if (empty($data)) {
            ApiResponse::returnMsg(200, 'success', $message);
        } else {
            ApiResponse::returnMsg(200, 'success', $message, $data);
        }
    }

    /**
     * 返回失败
     * @param string $message
     * @param array $data
     */
    public static function returnError($message = '', $code = 500)
    {
        ApiResponse::returnMsg($code, 'error', $message);
    }

    /**
     * 返回警告
     * @param string $message
     * @param array $data
     */
    public static function returnWarning($message = '')
    {
        ApiResponse::returnMsg(200, 'warning', $message);
    }
}